package com.interview.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Set;

import static com.interview.UserApplication.tokenMap;
import static com.interview.UserApplication.userRoleMap;

@Aspect
@Component
@Slf4j
public class LogAspectHandler {
    /**
     * 在上面定义的切面方法之前执行该方法
     * @param
     */
    @Pointcut("@annotation(com.interview.aspect.User)")
    public void pointCut() {}
    
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) throws Exception {

        // 也可以用来记录一些信息，比如获取请求的 URL 和 IP
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 获取请求 URL
        String url = request.getRequestURL().toString();
        // 获取请求 IP
        String ip = request.getRemoteAddr();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取切入点所在的方法对象
        Method method = signature.getMethod();
        String token = request.getHeader("token");

        if (StringUtils.isEmpty(token)){
            throw new Exception("用戶还没登录");
        }
        if (CollectionUtils.isEmpty(tokenMap)){
            throw new Exception("用戶还没登录");
        }
        Long id = tokenMap.get(token);
        Set<String> roleSet = userRoleMap.get(id.toString());

        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation.annotationType()== User.class) {
                if (roleSet.contains("NormalUser")){
                    System.out.println("角色权限校验通过");
                }else {
                    throw new Exception("角色权限校验失败");
                }
            }
            if (annotation.annotationType()== Editor.class) {
                if (roleSet.contains("Editor")){
                    System.out.println("角色权限校验通过");
                }else {
                    throw new Exception("角色权限校验失败");
                }
            }
        }

    }
}
